import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, clearToken , getName, clearName } from '@/utils/authToken'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: getName(),
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = getName()
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  /*login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },*/

  // get user info
  async getInfo({ commit, state }) {
    const res = await getInfo()
    if (res.success === true) {
      const { name } = res.data
      commit('SET_NAME', name)
    } else {
      clearToken()
    }
  },

  // user logout
  async logout({ commit, state }) {
    const res = await logout()
    commit('RESET_STATE')
    clearToken()
    clearName()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  // namespaced: true,
  state,
  mutations,
  actions
}

